package sisi.captains;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Decimalbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import javax.persistence.EntityManager;

import sisi.General;

/**
 * CaptainWindow.java - Controller class for <i>Captains window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 03/12/2013
 * 
 */
@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class CaptainWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {
//window
private Window windowCaptain, windowEditCaptain;
private Textbox tbCerca;
private Listbox boxCaptain;
private List lista_Captain;
private boolean lNuovo;
private Toolbarbutton buttonSeleziona;
private ListModelList listModelList;
private Integer idSelezionato = 0;

protected Map<String, Object> args;
private Object CaptainItem;
private Captain modCaptain;
// edit
private Textbox address;
private Textbox note;
private Intbox id;
private Textbox position;
private Textbox email;
private Textbox fax;
private Datebox birthdt;
private Textbox boat;
private Textbox city;
private Textbox contactname;
private Textbox country;
private Datebox dtup;
private Textbox gsm;
private Textbox longdiscode;
private Textbox region;
private Textbox telnum;
private Textbox zip;

		public void onCreate$windowCaptain(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N": tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		lista_Captain = new CaptainController().getList(null);
		listModelList.addAll(lista_Captain);
		boxCaptain.setModel(listModelList);
		boxCaptain.setItemRenderer(new CaptainItemRenderer());

		if (idSelezionato!=null && idSelezionato!=0){
		for (int i = 0; i < lista_Captain.size(); i++) {
			Captain record = (Captain)lista_Captain.get(i);
			if (record.getId()==idSelezionato.intValue()){
				boxCaptain.setSelectedIndex(i);
				break;
			}
		}
	}

}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}

	public void onClick$buttonCerca(Event event) {
		cerca();
	}


	private void cerca(){
		listModelList = new ListModelList();
		lista_Captain = new CaptainController().getList(tbCerca.getValue());
		listModelList.addAll(lista_Captain);
		boxCaptain.setModel(listModelList);
		boxCaptain.setItemRenderer(new CaptainItemRenderer());
	}

	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}

	public void onClick$buttonSeleziona(Event event) {

		seleziona();

}

	public void seleziona() {
		if (boxCaptain.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oCaptain = boxCaptain.getSelectedItem().getAttribute("rigaCaptain");
			String codiceSelezionato = ""+((Captain) oCaptain).getId();
			Sessions.getCurrent().setAttribute("codiceCaptainSelezionato", codiceSelezionato);
			windowCaptain.detach();
		}
	}

	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}

	private void modifica(boolean nuovo){
		try {

			int nIndex = boxCaptain.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Selezionare una riga da modificare", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxCaptain", boxCaptain);
				Window finestraEditCaptain = (Window) Executions.createComponents("/editCaptain.zul", null, map);
				finestraEditCaptain.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}

	public void onClick$buttonCancella(Event event) {
	// TODO Auto-generated method stub

	}

	public class CaptainItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Captain) data).getId()).setParent(li);
			new Listcell(""+((Captain) data).getContactname()).setParent(li);
			li.setAttribute("rigaCaptain", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}


// EDIT: NEW/MODIFY
	public void onCreate$windowEditCaptain(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();

		boxCaptain = (Listbox) args.get("boxCaptain");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			CaptainItem = boxCaptain.getSelectedItem().getAttribute("rigaCaptain");
			modCaptain = new CaptainController().refresh((Captain) CaptainItem);
			CaptainItem = modCaptain;
			windowEditCaptain.setTitle("Edit Captain");
			//categoryname.setFocus(true);
			//id.setValue(modCategorie.getCategoryid());
			//categoryname.setValue(modCategorie.getCategoryname());
			//description.setValue(modCategorie.getDescription());
			address.setValue(General.toUpperAncheNull(modCaptain.getAddress()));
			note.setValue(modCaptain.getNote());
			id.setValue(modCaptain.getId());
			position.setValue(General.toUpperAncheNull(modCaptain.getPosition()));
			email.setValue(modCaptain.getEmail());
			fax.setValue(modCaptain.getFax());
			birthdt.setValue( (java.util.Date) (modCaptain.getBirthdt()));
			boat.setValue(General.toUpperAncheNull(modCaptain.getBoat()));
			city.setValue(General.toUpperAncheNull(modCaptain.getCity()));
			contactname.setValue(General.toUpperAncheNull(modCaptain.getContactname()));
			country.setValue(General.toUpperAncheNull(modCaptain.getCountry()));
			dtup.setValue( (java.util.Date) (modCaptain.getDtup()));
			gsm.setValue(modCaptain.getGsm());
			longdiscode.setValue(modCaptain.getLongdiscode());
			region.setValue(General.toUpperAncheNull(modCaptain.getRegion()));
			telnum.setValue(modCaptain.getTelnum());
			zip.setValue(modCaptain.getZip());
		} else {
			windowEditCaptain.setTitle("New Captain");
			//categoryname.setFocus(true);
		}

	}

	public void onClick$btnAnnulla(Event event){
		windowEditCaptain.detach();
	}

	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modCaptain = new Captain();
		} else {

		}
		String testoMsg = "";

		modCaptain.setAddress(General.toUpperAncheNull(address.getValue()));
		modCaptain.setNote(note.getValue());
		modCaptain.setId(id.getValue());
		modCaptain.setPosition(General.toUpperAncheNull(position.getValue()));
		modCaptain.setEmail(email.getValue());
		modCaptain.setFax(fax.getValue());
		modCaptain.setBirthdt( (birthdt.getValue() != null ? (java.sql.Date) sisi.General.date2Sql(birthdt.getValue()): null) );
		modCaptain.setBoat(General.toUpperAncheNull(boat.getValue()));
		modCaptain.setCity(General.toUpperAncheNull(city.getValue()));
		modCaptain.setContactname(General.toUpperAncheNull(contactname.getValue()));
		modCaptain.setCountry(General.toUpperAncheNull(country.getValue()));
		modCaptain.setDtup( (dtup.getValue() != null ? (java.sql.Date) sisi.General.date2Sql(dtup.getValue()): null) );
		modCaptain.setGsm(gsm.getValue());
		modCaptain.setLongdiscode(longdiscode.getValue());
		modCaptain.setRegion(General.toUpperAncheNull(region.getValue()));
		modCaptain.setTelnum(telnum.getValue());
		modCaptain.setZip(zip.getValue());

		if (lNuovo){
			new CaptainController().add(modCaptain);
			testoMsg = "New Captain: "+ General.trimNull( modCaptain.getContactname() );
		} else {
			new CaptainController().update(modCaptain);
			testoMsg = "Update Captain: "+ General.trimNull( modCaptain.getContactname() );
		}

		General.showNotify( testoMsg, windowEditCaptain);

		windowEditCaptain.detach();

		// aggiorna listbox

		if (lNuovo){
			ListModelList lml = (ListModelList) boxCaptain.getListModel();
			lml.add(modCaptain);
			boxCaptain.setSelectedIndex(lml.indexOf(modCaptain));
		} else {
			ListModelList lml = (ListModelList) boxCaptain.getListModel();
			Object oCaptainItem = boxCaptain.getSelectedItem().getAttribute("rigaCaptain");
			if (lml.indexOf(oCaptainItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oCaptainItem), modCaptain);
			}
		}
	}

}
//
// fine
